import Request from '@/js_sdk/luch-request/luch-request/index.js'
export const apiBaseUrl = 'https://viptest.babybear.cn'
export default{
	myBaseUrl:"https://viptest.babybear.cn"
}

const api = new Request()
const http = new Request()

http.config.header = {
	"Content-Type": "application/x-www-form-urlencoded",
	"Authorization": uni.getStorageSync('authorization') ? uni.getStorageSync('authorization') :
		"Basic c3RvcmUtcGM6c3RvcmUtcGM="
}
api.config.header = {
	"Content-Type": "application/x-www-form-urlencoded",
	"Authorization": uni.getStorageSync('authorization') ? uni.getStorageSync('authorization') :
		"Basic c3RvcmUtcGM6c3RvcmUtcGM="
}

/* 设置全局配置 */
api.setConfig((config) => {
	config.header = {
		...config.header
	}
	return config
})


//请求前拦截，用来动态加参,例如token
api.interceptors.request.use((config) => { // 可使用async await 做异步操作
	config.baseURL = apiBaseUrl
	config.header = {
		...config.header,
	}

	//演示 authorization 用处
	var authorization = uni.getStorageSync('authorization');
	if(authorization) config.header.Authorization = authorization;

	if(config.method == 'GET'){
		uni.showLoading({
			title: '数据加载中...',
			mask: true
		})
	}

	if (config.custom.loadingMsg) {
		uni.showLoading({
			title: config.custom.loadingMsg,
			mask: true
		})
	}
	return config
}, config => { // 可使用async await 做异步操作
	return Promise.reject(config)
})


// 请求后
api.interceptors.response.use(async (response) => {
	if (response.config.custom.loadingMsg || response.config.method == 'GET') {
		setTimeout(function() {
			uni.hideLoading();
		}, 500)
	}
	
	
	if(response.statusCode == 200){
		if(response.data.code){
			if(response.data.code != 0){
				uni.showToast({
					title: response.data.msg,
					icon: 'none'
				})
			}
		}
	}
	
	return response
}, (response) => {
	uni.hideLoading();
	
	if (response.statusCode == 401) {
		uni.showToast({
			title: response.data.msg,
			icon: 'none'
		})
		
		uni.clearStorageSync();
		setTimeout(function (){
			uni.reLaunch({
				url: '/pages/welcome/welcome'
			})
		}, 500)
	} else {
		uni.showToast({
			title: '系统繁忙，请稍后再试~',
			icon: 'none'
		})
	}

	return Promise.reject(response)
})


export {
	http,
	api
}
